package com.coocaa.x.service.litedaemon.daemons.tvpie.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.CancelRunnable;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.liteccconnector.aidl.ILiteCCConnectorHandler;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litedaemon.daemons.tvpie.player.PlayerConstants.PlayerStatus;
import com.coocaa.x.service.litedaemon.daemons.tvpie.player.ResourceData.CLARITY;
import com.coocaa.x.service.liteplayer.aidl.ILitePlayerListener;
import com.coocaa.x.service.liteplayer.aidl.ReadyInfo;
import com.coocaa.x.service.liteplayer.aidl.VideoSourceInfo;
import com.coocaa.x.service.liteplayer.aidl.VideoSourceInfo.Clarityitem;
import com.skyworth.deservice.DEDefine;
import com.skyworth.deservice.api.def.SRTDEServicesCmdDef.SkyDEServiceCommandEnum;
import com.skyworth.deservice.api.def.SRTDEServicesCmdDef.SkyDEServiceInfoEnum;
import com.skyworth.framework.skysdk.util.SkyJSONUtil;
import com.skyworth.plugin.parser.jni.DownloadPlayerPlugin;
import com.skyworth.plugin.parser.jni.videoinfo;
import com.skyworth.plugin.parser.jni.videoparse;
import com.skyworth.webSDK.webservice.base.ResultList;
import com.skyworth.webSDK.webservice.mediaFactory.Resource;
import com.skyworth.webSDK.webservice.mediaFactory.model.Media;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.SoFileBean;
import com.tianci.de.api.DEChannelSession;
import com.tianci.de.api.JsonParams;
import com.tianci.de.define.DEPlayerDef;
import com.tianci.de.define.DEPlayerInfo;

public class TVPiePlayerDaemon extends LiteDaemon {
    private static interface CoocaaCmdHandler {
        public byte[] onHandle(String cmd, String json);
    }

    public static interface PlayerCallBack {
        public void onPlayerInit(String name, int totalTime);

        public void onPlayerProgressBack(int currentTime, int totalTime);

        public void onPlayerStatusBack(PlayerStatus status);
    }

    private static LiteDaemonInfo info = null;

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.tvpie.player";
        info.name = "电视派";
    }

    private static final String TAG = "tvpie";
    private static final String APP_SESSION = "tianci_appstore";

    private HashMap<String, CoocaaCmdHandler> mCmdHandlerMap = new HashMap<String, CoocaaCmdHandler>();

    private Handler soUpdateHandler = null;
    private PlayerCallBack mPlayerCallBack = null;
    private Resource<Media> mMediaResource = null;
    private List<Media> mCurrentMedias = new ArrayList<Media>();
    private videoparse mVideoparse = null;
    private String mLastMediaId = "";
    private Thread mPlayThread = null;
    private CancelRunnable mRunnable = null;
    private videoinfo mCurrentVideoInfo = null;
    private videoinfo mNextVideoInfo = null;
    private boolean mChangeSource = false;
    private ResourceData mCurrentData = new ResourceData();
    private DEPlayerInfo mInfo = new DEPlayerInfo();
    private DEPlayerInfo mNextInfo = new DEPlayerInfo();

    public TVPiePlayerDaemon() {
        super(info);
    }

    @Override
    protected void onCreate(Context context) {
        boolean isTianciSystem = CoocaaApplication.isCoocaaSystem();
        LogUtils.d(TAG, "TVPiePlayerDaemon 22 onCreate" + isTianciSystem);
        if (isTianciSystem)
            return;
        try {
            DownloadPlayerPlugin.setContext(context);
            createMediaResource();
            initUpdateHandler();
            initCmdHandler();
            initPlayerCallBack();
            XServiceManager.getLitePlayerClientService().getPlayerMonitor()
                    .addPlayerListener(playerListener);
            XServiceManager.getLiteCCConnectorService().addHandler(ccconnectorHandler);
            checkPlayerPlugin();
        } catch (Exception e) {
            LogUtils.d(TAG, "TVPiePlayerDaemon  onCreate  error!!");
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            XServiceManager.getLitePlayerClientService().getPlayerMonitor()
                    .removePlayerListener(playerListener);
            XServiceManager.getLiteCCConnectorService().removeHandler(ccconnectorHandler);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void initUpdateHandler() {
        soUpdateHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                LogUtils.d(TAG, "initUpdateHandler...");
                try {
                    SoFileBean soData = (SoFileBean) msg.obj;
                    boolean isTianciSystem = CoocaaApplication.isCoocaaSystem();
                    LogUtils.d(TAG, "updateHandler---isTianciSystem:" + isTianciSystem + " url:"
                            + soData.fileUrl);
                    DownloadPlayerPlugin.getInstance().checkPluginLib(isTianciSystem, soData); // 测试时用false
                } catch (Exception e) {
                    LogUtils.d(TAG, "initUpdateHandler..error.");
                    e.printStackTrace();
                }
            }
        };
    }

    private void checkPlayerPlugin() {
        LogUtils.d(TAG, "checkPlayerPlugin----------------");
        String version = "0";
        try {
            version = XServiceManager.getLiteConfigService().getStringValue("pluginversion", "0");
            LogUtils.d(TAG, "checkPlayerPlugin-----------version:" + version);
        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            LogUtils.d(TAG, "checkPlayerPlugin----------error------");
        }
        final String _version = version;
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                SoFileBean data = null;
                try {
                    LogUtils.d(TAG, "run------begin!!");
                    data = CoocaaApplication.getCoocaaWebService().getAppStoreService().getSoFile(_version);
                    LogUtils.d(TAG, "run----------------(data == null):" + (data == null));
                    if (data != null) {
                        Message msg = new Message();
                        msg.obj = data;
                        soUpdateHandler.sendMessage(msg);
                    }
                } catch (AppStoreException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    LogUtils.d(TAG, "run------error!!");
                }
            }
        }).start();
    }

    private void initCmdHandler() {
        // LogUtils.d(TAG, "initCmdHandler  ");
        mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_PLAYER_PLAY.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, final String json) {
                        LogUtils.d(TAG, "SKY_COMMAND_PLAYER_PLAY   !!!!!!!!");
                        post(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d(TAG, "SKY_COMMAND_PLAYER_PLAY   in thread...");
                                if (mPlayThread != null) {
                                    mPlayThread.interrupt();
                                }
                                if (mRunnable != null) {
                                    mRunnable.cancel();
                                }
                                LogUtils.d(TAG, "SKY_COMMAND_PLAYER_PLAY  222 in thread...");
                                mRunnable = new CancelRunnable() {
                                    public void run() {
                                        LogUtils.d(TAG, " get commond SKY_COMMAND_PLAYER_PLAY");
                                        mChangeSource = false;
                                        mNextInfo = new DEPlayerInfo();
                                        mNextVideoInfo = null;
                                        String source = "";
                                        if (mCurrentData != null) {
                                            source = mCurrentData.getCurrentSource();
                                        }
                                        mCurrentData = new ResourceData();
                                        mCurrentData.setCurrentSource(source);
                                        final MediaData mediaData = SkyJSONUtil.getInstance()
                                                .parseObject(json, MediaData.class);
                                        synchronized (mCurrentMedias) {
                                            if (!mLastMediaId.equals(mediaData.getId())) {
                                                mCurrentMedias.clear();
                                            }
                                        }
                                        if (mediaData.getMediaType().equals("MEDIA_VIDEO")) {
                                            LogUtils.d(TAG, "000 SKY_COMMAND_PLAYER_PLAY  isCancel:"
                                                    + isCancel());
                                            if (isCancel()) {
                                                return;
                                            }
                                            try {
                                                ReadyInfo info = new ReadyInfo();
                                                info.name = mediaData.getName();
                                                XServiceManager.getLitePlayerClientService()
                                                        .getPlayer().getReady(info);
                                            } catch (RemoteException e1) {
                                                // TODO Auto-generated catch block
                                                e1.printStackTrace();
                                            }
                                            String url = mediaData.getPreUrl();
                                            if (url == null || url.equals("") || url.equals("null")) {
                                                url = mediaData.getUrl();
                                            }
                                            if ("0".equals(mediaData.getParseStatus())) {
                                                mCurrentVideoInfo = null;
                                                try {
                                                    LogUtils.d(TAG, "begin to prase");
                                                    mVideoparse.stopParse();
                                                    mCurrentVideoInfo = mVideoparse.getParse(url);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                if (mCurrentVideoInfo == null) {
                                                    LogUtils.d(TAG,
                                                            " SKY_COMMAND_PLAYER_PLAY  mCurrentVideoInfo is null"
                                                                    + isCancel());
                                                    // mPlayerExtentionApi.start(null, "",
                                                    // ERROT_TYPE.PARSE_ERROR.toString());
                                                    try {
                                                        XServiceManager
                                                                .getLitePlayerClientService()
                                                                .getPlayer()
                                                                .errorOccurred("PARSE_ERROR", "");
                                                    } catch (RemoteException e) {
                                                        // TODO Auto-generated catch block
                                                        e.printStackTrace();
                                                    }
                                                    return;
                                                }
                                                if (mCurrentVideoInfo.isLive == 1) {
                                                    // mPlayerExtentionApi.startLive(
                                                    // checkURL(mCurrentVideoInfo),
                                                    // mediaData.getName());
                                                    LogUtils.d(TAG,
                                                            " SKY_COMMAND_PLAYER_PLAY  mCurrentVideoInfo is live!"
                                                                    + isCancel());
                                                    try {
                                                        XServiceManager
                                                                .getLitePlayerClientService()
                                                                .getPlayer()
                                                                .start(getVideoSourceInfo(mCurrentVideoInfo),
                                                                        mediaData.getName());
                                                    } catch (RemoteException e) {
                                                        // TODO Auto-generated catch block
                                                        e.printStackTrace();
                                                    }
                                                    return;
                                                }
                                                LogUtils.d(TAG, "111 SKY_COMMAND_PLAYER_PLAY  isCancel:"
                                                        + isCancel());
                                                if (isCancel()) {
                                                    return;
                                                }
                                                try {
                                                    XServiceManager
                                                            .getLitePlayerClientService()
                                                            .getPlayer()
                                                            .start(getVideoSourceInfo(mCurrentVideoInfo),
                                                                    mediaData.getName());
                                                } catch (RemoteException e1) {
                                                    // TODO Auto-generated catch block
                                                    e1.printStackTrace();
                                                }
                                                // mPlayerExtentionApi.setNextVideo("", null);
                                                mediaData
                                                        .setChildId(mCurrentVideoInfo.CurrentSegment);
                                                int childId = 0;
                                                if (mediaData.getChildId() != null
                                                        && !mediaData.getChildId().equals("")) {
                                                    childId = Integer.valueOf(mediaData
                                                            .getChildId());
                                                }
                                                mInfo.currentEpisode = childId;
                                                mNextInfo.currentEpisode = childId;
                                                if (mediaData.getChildId() != null
                                                        && !mediaData.getChildId().equals("")
                                                        && mediaData.getId() != null
                                                        && !mediaData.getId().equals("")
                                                        && (!mLastMediaId.equals(mediaData.getId()) || mCurrentMedias
                                                        .size() == 0)) {
                                                    try {
                                                        LogUtils.d(TAG,
                                                                "22 SKY_COMMAND_PLAYER_PLAY  isCancel:"
                                                                        + isCancel());
                                                        if (isCancel()) {
                                                            return;
                                                        }
                                                        mLastMediaId = mediaData.getId();
                                                        ResultList<Media> mediaResult = mMediaResource
                                                                .listSegments(mediaData.getId(), 0,
                                                                        100,
                                                                        mCurrentVideoInfo.Source);
                                                        if (isCancel()) {
                                                            return;
                                                        }
                                                        if (mediaResult.result != null
                                                                && childId < mediaResult.result
                                                                .size()) {
                                                            synchronized (mCurrentMedias) {
                                                                if (mLastMediaId == mediaData
                                                                        .getId()) {
                                                                    mCurrentMedias = mediaResult.result;
                                                                    mInfo.totalEpisode = mCurrentMedias
                                                                            .size();
                                                                    LogUtils.d("get current media size is "
                                                                            + mCurrentMedias.size());
                                                                }
                                                                if (mNextVideoInfo == null) {
                                                                    setNextVideoUrl();
                                                                    mChangeSource = true;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                                generateResourceData();
                                            } else {
                                                try {
                                                    XServiceManager
                                                            .getLitePlayerClientService()
                                                            .getPlayer()
                                                            .start(getVideoSourceInfo(mCurrentVideoInfo),
                                                                    mediaData.getName());
                                                } catch (RemoteException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                        } else {
                                            // TipToast.getInstance(mContext).showTipToast(
                                            // mContext.getResources().getString(
                                            // R.string.not_support_type));
                                        }
                                    }

                                    ;
                                };
                                mPlayThread = new Thread(mRunnable);
                                mPlayThread.start();
                            }
                        });
                        return null;
                    }
                });

        mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_PLAYER_PLAY_OR_PAUSE.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, String json) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d(TAG, " get commond SKY_COMMAND_PLAYER_PLAY_OR_PAUSE");
                                try {
                                    boolean playing = XServiceManager.getLitePlayerClientService()
                                            .getPlayer().isPlaying();
                                    LogUtils.d(TAG, "the current status is " + playing);
                                    if (playing) {
                                        XServiceManager.getLitePlayerClientService().getPlayer()
                                                .pause();
                                    } else {
                                        XServiceManager.getLitePlayerClientService().getPlayer()
                                                .resume();
                                    }
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return null;
                    }
                });

        mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_PLAYER_SEEK.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, final String json) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d(TAG, " get commond SKY_COMMAND_PLAYER_SEEK" + " params is "
                                        + json);
                                try {
                                    int seek = Integer.valueOf(json);
                                    XServiceManager.getLitePlayerClientService().getPlayer()
                                            .seekTo(seek);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return null;
                    }
                });

        mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_PLAYER_STOP.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, String json) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d(" get commond SKY_COMMAND_PLAYER_STOP");
                                try {
                                    XServiceManager.getLitePlayerClientService().getPlayer().stop();
                                } catch (RemoteException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        });
                        return null;
                    }
                });

        // mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_GET_APPINFO.toString(),
        // new CoocaaCmdHandler()
        // {
        // @Override
        // public byte[] onHandle(String cmd, String json)
        // {
        // post(new Runnable()
        // {
        // @Override
        // public void run()
        // {
        // final DEChannelSession session = new DEChannelSession(
        // new JsonParams(APP_SESSION, "notify",
        // SkyDEServiceInfoEnum.SKY_INFO_GET_PLAYDATA
        // .toString(), mInfo.toString()));
        // session.authSession(DEPlayerDef.LOCAL_IP, "5555",
        // DEPlayerDef.DIAN_SHI_PAI);
        //
        // try
        // {
        // XServiceManager.getLiteCCConnectorService().writeDEChannel(
        // session.toSerialize());
        // } catch (RemoteException e)
        // {
        // }
        // }
        // });
        // return null;
        // }
        // });
        //
        // mCmdHandlerMap.put("SKY_COMMAND_APPSTORE_CLOSE_APP", new CoocaaCmdHandler()
        // {
        // @Override
        // public byte[] onHandle(String cmd, final String json)
        // {
        // post(new Runnable()
        // {
        // @Override
        // public void run()
        // {
        // try
        // {
        // JSONObject jsonObject = JSONObject.parseObject(json);
        // ServiceFacotry.getAppService().forceStopProcess(
        // jsonObject.getString("pkgName"));
        // } catch (Exception e)
        // {
        // e.printStackTrace();
        // }
        // }
        // });
        // return null;
        // }
        // });
        mCmdHandlerMap.put(SkyDEServiceInfoEnum.SKY_INFO_GET_RESOURCEDATA.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, final String json) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                final DEChannelSession session = new DEChannelSession(
                                        new JsonParams(APP_SESSION, "notify",
                                                SkyDEServiceInfoEnum.SKY_INFO_GET_RESOURCEDATA
                                                        .toString(), mCurrentData.toString()));
                                session.authSession(DEPlayerDef.LOCAL_IP, "5555",
                                        DEPlayerDef.DIAN_SHI_PAI);
                                try {
                                    XServiceManager.getLiteCCConnectorService().writeDEChannel(
                                            session.toSerialize());
                                } catch (RemoteException e) {
                                }
                            }
                        });
                        return null;
                    }
                });

        mCmdHandlerMap.put(SkyDEServiceCommandEnum.SKY_COMMAND_DONGLE_SWITCH_SOURCE.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(String cmd, final String json) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d(" get commond SKY_COMMAND_DONGLE_SWITCH_SOURCE and the params is "
                                        + json);
                                changeSource(json);
                            }
                        });
                        return null;
                    }
                });
    }

    private VideoSourceInfo getVideoSourceInfo(videoinfo info) {
        VideoSourceInfo vInfo = new VideoSourceInfo();
        List<Clarityitem> list = new ArrayList<Clarityitem>();
        vInfo.url = checkURL(info).toString();
        vInfo.extra = info.toJSONString();
        if (info.NomalUrl != null && !info.NomalUrl.equals("")) {
            Clarityitem item = new Clarityitem(1, info.NomalUrl);
            list.add(item);
        }
        if (info.HighUrl != null && !info.HighUrl.equals("")) {
            Clarityitem item2 = new Clarityitem(2, info.HighUrl);
            list.add(item2);
        }
        if (info.SupreUrl != null && !info.SupreUrl.equals("")) {
            Clarityitem item3 = new Clarityitem(3, info.SupreUrl);
            list.add(item3);
        }
        vInfo.clarityitemList = list;
        return vInfo;
    }

    private void initPlayerCallBack() {
        // LogUtils.d(TAG,"initPlayerCallBack ");
        mPlayerCallBack = new PlayerCallBack() {
            @Override
            public void onPlayerInit(String name, int totalTime) {
                mInfo.resourceName = name;
                mInfo.totalTime = totalTime;
                mInfo.type = 0;
                mInfo.curTime = 0;
                mInfo.isPausing = false;
                mInfo.isPlaying = true;
                final String cmd = DEPlayerDef.CMD_CTRL;
                post(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.d("b2p", "send player init ");
                        final DEChannelSession session = new DEChannelSession(new JsonParams(
                                APP_SESSION, "notify", cmd, mInfo.toString()));
                        session.authSession(DEPlayerDef.LOCAL_IP, "5555", DEPlayerDef.DIAN_SHI_PAI);
                        try {
                            XServiceManager.getLiteCCConnectorService().writeDEChannel(
                                    session.toSerialize());
                        } catch (RemoteException e) {
                        }
                    }
                });
            }

            @Override
            public void onPlayerProgressBack(int currentTime, int totalTime) {
                // TODO Auto-generated method stub
                mInfo.curTime = currentTime;
                final String cmd = DEPlayerDef.CMD_SEEK;
                final StringBuilder builder = new StringBuilder();
                builder.append(currentTime).append("/").append(totalTime);
                post(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.d("b2p", "send player progress ");
                        final DEChannelSession session = new DEChannelSession(new JsonParams(
                                APP_SESSION, "notify", cmd, builder.toString()));
                        session.authSession(DEPlayerDef.LOCAL_IP, "5555", DEPlayerDef.DIAN_SHI_PAI);
                        try {
                            XServiceManager.getLiteCCConnectorService().writeDEChannel(
                                    session.toSerialize());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onPlayerStatusBack(PlayerStatus status) {
                LogUtils.d("b2p", "send player status: " + status);
                final String cmd = DEPlayerDef.CMD_CTRL;
                switch (status) {
                    case PAUSED:
                        mInfo.isPausing = true;
                        mInfo.isPlaying = false;
                        break;
                    case PLAYNEXT:
                        LogUtils.d("will play next video");
                        mCurrentVideoInfo = mNextVideoInfo;
                        String source = "";
                        if (mCurrentData != null) {
                            source = mCurrentData.getCurrentSource();
                        }
                        mCurrentData = new ResourceData();
                        mCurrentData.setCurrentSource(source);
                        generateResourceData();
                        return;
                    case STARTED:
                        LogUtils.d("current episode is " + mInfo.currentEpisode
                                + " and next episode is " + mNextInfo.currentEpisode);
                        LogUtils.d("total media size is " + mCurrentMedias.size());
                        synchronized (mCurrentMedias) {
                            LogUtils.d("the current source count is "
                                    + mCurrentData.getSourceCount());
                            if (mCurrentData.getSourceCount() >= 1) {
                                final DEChannelSession session = new DEChannelSession(
                                        new JsonParams(APP_SESSION, "notify",
                                                SkyDEServiceInfoEnum.SKY_INFO_GET_RESOURCEDATA
                                                        .toString(), mCurrentData.toString()));
                                session.authSession(DEPlayerDef.LOCAL_IP, "5555",
                                        DEPlayerDef.DIAN_SHI_PAI);
                                try {
                                    XServiceManager.getLiteCCConnectorService().writeDEChannel(
                                            session.toSerialize());
                                } catch (RemoteException e) {
                                }
                            }
                            LogUtils.d("need set next video url " + !mChangeSource);
                            if (!mChangeSource) {
                                if (mNextInfo.currentEpisode > 0
                                        && mNextInfo.currentEpisode < mCurrentMedias.size()) {
                                    setNextVideoUrl();
                                }
                            } else {
                                mChangeSource = false;
                            }
                        }
                    case RESUMED:
                        mInfo.isPlaying = true;
                        mInfo.isPausing = false;
                        break;
                    case COMPLETION:
                    case STOPED:
                        mInfo.type = -1;
                        mInfo.isPausing = true;
                        mInfo.isPlaying = true;
                        break;
                    default:
                        return;
                }
                post(new Runnable() {
                    @Override
                    public void run() {
                        final DEChannelSession session = new DEChannelSession(new JsonParams(
                                APP_SESSION, "notify", cmd, mInfo.toString()));
                        session.authSession(DEPlayerDef.LOCAL_IP, "5555", DEPlayerDef.DIAN_SHI_PAI);
                        try {
                            XServiceManager.getLiteCCConnectorService().writeDEChannel(
                                    session.toSerialize());
                        } catch (RemoteException e) {
                        }
                    }
                });
            }
        };
    }

    private void createMediaResource() {
        LogUtils.d(TAG, "createMediaResource  ");
        // TODO Auto-generated method stub
        mVideoparse = new videoparse();
        try {
            mMediaResource = CoocaaApplication
                    .getCoocaaWebService()
                    .getWebComplexFactory()
                    .getClassInstance(Resource.class, Media.class,
                            Resource.Factory.tianci.toString());
        } catch (Exception e) {
            LogUtils.d(TAG, "createMediaResource  error!!");
            e.printStackTrace();
        }
        LogUtils.d(TAG, "createMediaResource  success!!");
    }

    private void setNextVideoUrl() {
        // Media media = mCurrentMedias.get(mNextInfo.currentEpisode);
        // if (media.sources != null && media.sources.size() > 0)
        // {
        // try
        // {
        // mNextVideoInfo = mVideoparse.getParse(media.sources.get(0).url);
        // String url = checkURL(mNextVideoInfo);
        // mNextInfo.resourceName = media.title;
        // mPlayerExtentionApi.setNextVideo(media.title, url);
        // LogUtils.d("set next media title is " + media.title + " and the url is " + url);
        // mNextInfo.currentEpisode++;
        // } catch (Exception e)
        // {
        // mPlayerExtentionApi.setNextVideo("", "");
        // e.printStackTrace();
        // }
        // }
    }

    private void changeSource(String source) {
        // String url = "";
        // String clarity = "";
        // if (CLARITY.SOURCE_HD.toString().equals(source))
        // {
        // url = mCurrentVideoInfo.HighUrl;
        // mCurrentData.setCurrentSource(CLARITY.SOURCE_HD.toString());
        // clarity = mContext.getResources().getString(R.string.high_definition);
        // } else if (CLARITY.SOURCE_SD.toString().equals(source))
        // {
        // url = mCurrentVideoInfo.NomalUrl;
        // mCurrentData.setCurrentSource(CLARITY.SOURCE_SD.toString());
        // clarity = mContext.getResources().getString(R.string.standard_definition);
        // } else if (CLARITY.SOURCE_UD.toString().equals(source))
        // {
        // url = mCurrentVideoInfo.SupreUrl;
        // mCurrentData.setCurrentSource(CLARITY.SOURCE_UD.toString());
        // clarity = mContext.getResources().getString(R.string.super_definition);
        // }
        // if (!url.equals(""))
        // {
        // mPlayerExtentionApi.switchSrcLoading(mInfo.resourceName, clarity);
        // mPlayerExtentionApi.switchSource(url, mInfo.resourceName, mInfo.curTime);
        // mChangeSource = true;
        // if (mNextVideoInfo != null)
        // {
        // String nextUrl = checkURL(mNextVideoInfo);
        // LogUtils.d("set next media title is " + mNextVideoInfo.VideoTitle
        // + " and the url is " + nextUrl);
        // mPlayerExtentionApi.setNextVideo(mNextVideoInfo.VideoTitle, nextUrl);
        // }
        // }
    }

    private void generateResourceData() {
        mCurrentData.setCurrentEpisode(stringToInt(mCurrentVideoInfo.CurrentSegment));
        mCurrentData.setTotalEpisode(mCurrentMedias.size());
        mCurrentData.setResourceName(mCurrentVideoInfo.VideoTitle);
        mCurrentData.setResourceUrl(mCurrentVideoInfo.UnParseUrl);
        if (!stringIsNull(mCurrentVideoInfo.SupreUrl)) {
            mCurrentData.addSource(CLARITY.SOURCE_SD);
        }
        if (!stringIsNull(mCurrentVideoInfo.HighUrl)) {
            mCurrentData.addSource(CLARITY.SOURCE_HD);
        }
        if (!stringIsNull(mCurrentVideoInfo.NomalUrl)) {
            mCurrentData.addSource(CLARITY.SOURCE_UD);
        }
    }

    private int stringToInt(String num) {
        if (num != null && !num.equals("") && !num.equals("null")) {
            try {
                return Integer.valueOf(num);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
        return 0;
    }

    private boolean stringIsNull(String string) {
        if (string == null || string.equals("") || string.equals("null")) {
            return true;
        }
        return false;
    }

    private String getUrlBySource(videoinfo info) {
        if (mCurrentData.getCurrentSource().equals(CLARITY.SOURCE_HD.toString())) {
            if (!stringIsNull(info.HighUrl)) {
                return info.HighUrl;
            }
        } else if (mCurrentData.getCurrentSource().equals(CLARITY.SOURCE_SD.toString())) {
            if (!stringIsNull(info.NomalUrl)) {
                return info.NomalUrl;
            }
        } else if (mCurrentData.getCurrentSource().equals(CLARITY.SOURCE_UD.toString())) {
            if (!stringIsNull(info.SupreUrl)) {
                return info.SupreUrl;
            }
        }
        return "";
    }

    private Uri checkURL(videoinfo info) {
        String url = "";
        String nomalUrl = info.NomalUrl;
        if (mCurrentData != null && !mCurrentData.getCurrentSource().equals("")) {
            url = getUrlBySource(info);
            if (!stringIsNull(url)) {
                return Uri.parse(url);
            }
        }
        if (nomalUrl != null && !nomalUrl.equals("")) {
            mCurrentData.setCurrentSource(CLARITY.SOURCE_SD.toString());
            url = nomalUrl;
        }
        String superUrl = info.SupreUrl;
        if (superUrl != null && !superUrl.equals("")) {
            if (url.equals("")) {
                mCurrentData.setCurrentSource(CLARITY.SOURCE_UD.toString());
                url = superUrl;
            }
        }
        String highUrl = info.HighUrl;
        if (highUrl != null && !highUrl.equals("")) {
            if (url.equals("")) {
                mCurrentData.setCurrentSource(CLARITY.SOURCE_HD.toString());
                url = highUrl;
            }

            if (url.equals("")) {
                mCurrentData.setCurrentSource(CLARITY.SOURCE_HD.toString());
                url = highUrl;
            }
        }
        return Uri.parse(url);
    }

    private ILiteCCConnectorHandler.Stub ccconnectorHandler = new ILiteCCConnectorHandler.Stub() {
        private byte[] EMPTY = new byte[0];

        @Override
        public byte[] onHandler(String arg0, String arg1, byte[] arg2) throws RemoteException {
            if (arg1.equals(DEDefine.CmdEnum.CMD_READ_BY_DECHANNEL.toString())
                    || arg1.equals(DEDefine.CmdEnum.CMD_WRITE_BY_DECHANNEL.toString())) {
                if (arg2 != null) {
                    DEChannelSession session = DEChannelSession.getDEChannlSession(arg2);
                    LogUtils.v(TAG, "CMD_READ_BY_DECHANNEL == " + session.getJsonParam().getSession()
                            + session.getJsonParam().getType() + session.getJsonParam().getCmd()
                            + session.getJsonParam().getParam());
                    String json = session.getJsonParam().getParam();
                    CoocaaCmdHandler handler = mCmdHandlerMap.get(session.getJsonParam().getCmd()
                            .toString());
                    if (handler != null) {
                        handler.onHandle(session.getJsonParam().getCmd(), json);
                    }
                } else {
                    LogUtils.d(TAG, "CMD_WRITE_BY_DECHANNEL no received body!!");
                }
            }
            return EMPTY;
        }
    };

    private String vName = "";
    private int totalTime = 0;
    private int currentTime = 0;
    private PlayerStatus currentState = PlayerStatus.UNKNOW;

    private ILitePlayerListener.Stub playerListener = new ILitePlayerListener.Stub() {
        @Override
        public void onBufferingUpdate(int arg0) throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onBufferingUpdate....");
            currentState = PlayerStatus.BUFFERINGUPDATE;
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onCompletion() throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onCompletion....");
            currentState = PlayerStatus.COMPLETION;
            mPlayerCallBack.onPlayerStatusBack(currentState);

        }

        @Override
        public boolean onError(int arg0, int arg1) throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onError....");
            currentState = PlayerStatus.ERROR;
            mPlayerCallBack.onPlayerStatusBack(currentState);
            return false;
        }

        @Override
        public boolean onInfo(int arg0, int arg1) throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onInfo....");
            return false;
        }

        @Override
        public void onPlayPaused() throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onPlayPaused....");
            currentState = PlayerStatus.PAUSED;
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onPlayResumed() throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onPlayResumed....");
            currentState = PlayerStatus.RESUMED;
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onPlayStarted(String videoName, int durationInMilliSeconds)
                throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onPlayStarted....name:" + videoName + " duration:"
                    + durationInMilliSeconds);
            vName = videoName;
            totalTime = durationInMilliSeconds;
            currentState = PlayerStatus.STARTED;
            mPlayerCallBack.onPlayerInit(vName, durationInMilliSeconds);
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onPlayStopped() throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onPlayStopped....");
            currentState = PlayerStatus.STOPED;
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onPrepared() throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onPrepared....");
            currentState = PlayerStatus.PREPARED;
            mPlayerCallBack.onPlayerStatusBack(currentState);
        }

        @Override
        public void onProgressChanged(int timeInMilliSeconds) throws RemoteException {
            // TODO Auto-generated method stub
            LogUtils.d("b2p", "onProgressChanged....currenttime:" + timeInMilliSeconds);
            currentTime = timeInMilliSeconds;
            currentState = PlayerStatus.PROGRESSCHANGEED;
            mPlayerCallBack.onPlayerStatusBack(currentState);
            mPlayerCallBack.onPlayerProgressBack(currentTime, totalTime);
        }
    };

    // private ICustomListener.Stub customListener = new ICustomListener.Stub()
    // {
    //
    // @Override
    // public void onBufferingUpdate(int arg0) throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onBufferingUpdate....");
    // currentState = PlayerStatus.BUFFERINGUPDATE;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onCompletion() throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onCompletion....");
    // currentState = PlayerStatus.COMPLETION;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    //
    // }
    //
    // @Override
    // public boolean onError(int arg0, int arg1) throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onError....");
    // currentState = PlayerStatus.ERROR;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // return false;
    // }
    //
    // @Override
    // public boolean onInfo(int arg0, int arg1) throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onInfo....");
    // return false;
    // }
    //
    // @Override
    // public void onPlayPaused() throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onPlayPaused....");
    // currentState = PlayerStatus.PAUSED;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onPlayResumed() throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onPlayResumed....");
    // currentState = PlayerStatus.RESUMED;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onPlayStarted(String videoName, int durationInMilliSeconds) throws
    // RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onPlayStarted....name:"+videoName+" duration:"+durationInMilliSeconds);
    // vName = videoName;
    // totalTime = durationInMilliSeconds;
    // currentState = PlayerStatus.STARTED;
    // mPlayerCallBack.onPlayerInit(vName, durationInMilliSeconds);
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onPlayStopped() throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onPlayStopped....");
    // currentState = PlayerStatus.STOPED;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onPrepared() throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onPrepared....");
    // currentState = PlayerStatus.PREPARED;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // }
    //
    // @Override
    // public void onProgressChanged(int timeInMilliSeconds) throws RemoteException
    // {
    // // TODO Auto-generated method stub
    // LogUtils.d("b2p", "onProgressChanged....currenttime:"+timeInMilliSeconds);
    // currentTime = timeInMilliSeconds;
    // currentState = PlayerStatus.PROGRESSCHANGEED;
    // mPlayerCallBack.onPlayerStatusBack(currentState);
    // mPlayerCallBack.onPlayerProgressBack(currentTime, totalTime);
    // }
    //
    // };
}
